#include<iostream>
#include<string>
#include<cstdio>
#include<mysql/mysql.h>


const std::string host="127.0.0.1";
const std::string user="root";
const std::string password="";//后期修改
const std::string db="cool";//后期修改
const unsigned int port=3306;//后面修改
int main()
{
    //0.创建mysql句柄
    MYSQL *my=mysql_init(nullptr);
    //1.连接数据库
    if(mysql_real_connect(my,host.c_str(),user.c_str(),
    password.c_str(),db.c_str(),port,nullptr,0)==nullptr)//TODO
    {
        std::cout<<"connect failed"<<std::endl;
        return 1;
    }
    //1.设置链接的编码格式
    mysql_set_character_set(my,"utf8");
    //2.访问数据库
    std::string sql="select * from clothes where cloth_no=1";//要用啥改啥
    int res=mysql_query(my,sql.c_str());
    if(res!=0)
    {
        std::cout<<"execute:"<<sql<<"failed"<<std::endl;
        return 2;
    }
    //2.1解析数据
    MYSQL_RES* result=mysql_store_result(my);
    int rows=mysql_num_rows(result);
    int cols=mysql_num_fields(result);
    std::cout<<"行数："<<rows<<"列数："<<cols<<std::endl;
    //2.2获取表中列名
    MYSQL_FIELD *fields=mysql_fetch_fields(result);
    for(int i=0;i<cols;i++)
    {
        std::cout<<fields[i].name<<"\t";
    }
    std::cout<<std::endl;
    //2.3获取表中数据
    for(int i=0;i<rows;i++)
    {
        MYSQL_ROW line=mysql_fetch_row(result);//获取完整的一行记录
        for(int j=0;j<cols;j++)
        {
            std::cout<<line[j]<<"\t";
        }
        std::cout<<std::endl;
    }
    //3.关闭数据库
    free(result);
    mysql_close(my);

    return 0;
}